package com.lxu.report.service;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Pattern;

@Service
public class MultipleRowsCopyService {

    public void copy(XWPFTable table, int sourceIndex, int rowIndex, int index) {
        XWPFTableRow sourceRow = table.getRow(sourceIndex);
        //在表格指定位置新增一行
        table.addRow(sourceRow,rowIndex);
        List<XWPFTableCell> cellList = table.getRow(rowIndex).getTableCells();
        if (null == cellList) {
            return;
        }
        //复制列及其属性和内容
        for (int i=0;i<cellList.size();i++) {
            setCellText(cellList.get(i), index);
        }
    }

    private void setCellText(XWPFTableCell targetCell, int index) {
        String text = targetCell.getText();
        if (StringUtils.isNotBlank(text)) {
            int begin = text.trim().indexOf("${") + 2;
            int end = text.trim().indexOf("}");
            if (begin >= 0 && end >= 0) {
                StringBuffer sb = new StringBuffer().append("${").append(assemblePlaceHolder(text.trim().substring(begin,end))).append(index).append("}");
                targetCell.getParagraphs().get(0).getRuns().get(0).setText(sb.toString(),0);
            }
        }
    }

    private String assemblePlaceHolder(String placeHolder) {
        if(StringUtils.isBlank(placeHolder)){
            return "";
        }
        if(isInteger(placeHolder.substring(placeHolder.length()-3))){
            return placeHolder.substring(0,placeHolder.length()-3);
        }
        if(isInteger(placeHolder.substring(placeHolder.length()-2))){
            return placeHolder.substring(0,placeHolder.length()-2);
        }
        if(isInteger(placeHolder.substring(placeHolder.length()-1))){
            return placeHolder.substring(0,placeHolder.length()-1);
        }
        return placeHolder;
    }

    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }
}
